<template>
  <VfDataTable
    ref="tableRef"
    v-bind="tableOptions"
  >
    <template #toolbar_left>
      <!-- 新增行 -->
      <el-button plain size="small" type="primary" @click="handleAddRow('add')">新增行</el-button>
      <el-button plain size="small" type="danger" @click="handleDelRow('del')">删除行</el-button>
    </template>
    <template #param_render="{row, column}">
      <el-button
        size="small" round :icon="Edit"
        :type="row['paramRender'] ? 'primary' : 'default'"
        @click="codeEditorOpen({row, column})"
      />
    </template>
  </VfDataTable>
  <CodeEditorDialog
    ref="codeEditorRef"
    :="codeEditorAttrs"
    @confirm="codeEditorConfirm"
  />
</template>

<script setup>
import { VfDataTable } from '@/components/vf-table';
import { CodeEditorDialog } from '@/components/dialogs'

import { ref, reactive, watch, onBeforeMount } from 'vue';
import { Edit } from '@element-plus/icons-vue'

import { VfUtils } from '@/utils/vf-utils'
import { useDataHandle } from '@/components/tables/hook/useDataHandle'
import { useTableColumns } from './cfg/table-columns'
import { DEFAULT_PARAM_ROW } from '@/components/tables/cfg/table-cons'

const props = defineProps({
  fieldOptions: { type: Array, default: [] },
});

// 表格ref对象
const tableRef = ref(null)
// 表格配置
const tableOptions = reactive({
  data: [],
  height: 'auto',
  minHeight: 350,
  stripe: false,
  columns: [],
  loading: false,
  keyField: 'id',
  boxConfig: true,
  seqConfig: true,
  pagerConfig: false,
  showOverflow: 'ellipsis',
  toolbarConfig: { enabled: true, refresh: false },
});

/** 初始化表格字段 */
const initTableColumns = () => {
  const { fieldOptions } = props
  tableOptions.columns = useTableColumns().getColumns({ fieldOptions });
}

watch(
  () => props.fieldOptions,
  (newValue, oldValue) => {
    if (newValue && newValue.length) {
      initTableColumns();
    }
  },
  { deep: false, immediate: false },
);

const hooksParams = {
  props, tableRef, tableOptions, templateRow: DEFAULT_PARAM_ROW
}

// 表格数据操作
const {
  setTableData,
  getTableData,
  validateParamData,
  getPreviewTableData
} = useDataHandle(hooksParams)


/**
 * 添加新的行数据
 */
const handleAddRow = () => {
  const gridRef = tableRef.value;
  const rowItem = {
    "field": "",
    "title": "",
    "id": VfUtils.getUUID(),
    "level": 1,
    "parentId": 0,
    "kind": "string",
    "defaultValue": "",
    "paramRender": ""
  }
  gridRef.insertAt(rowItem, -1)
}
const handleDelRow = () => {
  const gridRef = tableRef.value;
  gridRef.removeCheckboxRow()
}

const validateTableData = () => {
  const validInfo = validateParamData()
  if (validInfo.valid) {
    return true
  } else {
    TableUtils.openMessage(`参数明细：${validInfo.msg}`)
    return false
  }
}

const codeEditorRef = ref(null)
// 代码编辑器属性
const codeEditorAttrs = reactive({
  title: '编写参数',
  frontAlert: 'function paramRender() {',
  showFooter: true,
});
const codeEditorStore = reactive({
  row: { paramRender: '' },
  column: { field: 'paramRender'  }
})
/**
 * 打开代码编辑器弹窗
 * 
 * @param param 表格数据
 */
const codeEditorOpen = ({ row, column }) => {
  codeEditorStore.row = row
  codeEditorStore.column = column
  codeEditorRef.value.handleOpen(row.paramRender)
}
/**
 * 代码编辑器弹窗确定按钮执行
 * 
 * @param result 编辑器结果
 */
const codeEditorConfirm = (result) => {
  const { row, column } = codeEditorStore
  row[column.field] = result
}

onBeforeMount(() => {
  tableOptions.loading = true
})

initTableColumns()

defineExpose({
  setTableData,
  getTableData,
  validateTableData,
  getPreviewTableData
})

</script>

<style lang="scss" scoped>
.el-input__icon {
  cursor: pointer;
}
</style>